{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import torch\n",
    "from torch.utils import data\n",
    "from d2l import torch as d2l"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [],
   "source": [
    "true_w = torch.tensor([2, -3.4])\n",
    "true_b = 4.2\n",
    "\n",
    "features, labels = d2l.synthetic_data(true_w, true_b, 1000)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [
    {
     "data": {
      "text/plain": "[tensor([[ 1.3536e+00, -9.1793e-01],\n         [-1.4704e+00,  5.6784e-01],\n         [-1.4335e+00,  4.8216e-01],\n         [ 1.7772e-02,  7.8170e-04],\n         [ 1.2915e-01, -4.1884e-01],\n         [ 2.4733e-01, -1.4330e+00],\n         [ 9.2165e-02, -1.1814e-01],\n         [-1.4287e+00, -3.6226e-01],\n         [ 2.6128e-01,  1.1545e+00],\n         [-1.3242e+00,  5.8073e-02]]),\n tensor([[10.0434],\n         [-0.6696],\n         [-0.3135],\n         [ 4.2389],\n         [ 5.8650],\n         [ 9.5587],\n         [ 4.7863],\n         [ 2.5741],\n         [ 0.7964],\n         [ 1.3528]])]"
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def load_array(data_arrays, batch_size, is_train=True):\n",
    "    dataset = data.TensorDataset(*data_arrays)   # *号用于解包\n",
    "    return data.DataLoader(dataset, batch_size, shuffle=is_train)\n",
    "\n",
    "batch_size = 10\n",
    "data_iter = load_array((features, labels), batch_size)\n",
    "next(iter(data_iter))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "outputs": [],
   "source": [
    "from torch import nn\n",
    "net = nn.Sequential(nn.Linear(2, 1))\n",
    "\n",
    "# 初始化模型参数\n",
    "net[0].weight.data.normal_(0, 0.01)\n",
    "net[0].bias.data.fill_(0)\n",
    "\n",
    "# 定义损失函数\n",
    "loss = nn.MSELoss()\n",
    "\n",
    "# 定义优化算法\n",
    "lr = 0.03\n",
    "trainer = torch.optim.SGD(net.parameters(), lr)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, loss 0.000096\n",
      "epoch 2, loss 0.000096\n",
      "epoch 3, loss 0.000096\n"
     ]
    }
   ],
   "source": [
    "# 训练\n",
    "num_epochs = 3\n",
    "for epoch in range(num_epochs):\n",
    "    for X, y in data_iter:\n",
    "        l = loss(net(X), y)\n",
    "        trainer.zero_grad()\n",
    "        l.backward()\n",
    "        trainer.step()\n",
    "    l = loss(net(features), labels)\n",
    "    print(f'epoch {epoch + 1}, loss {l:f}')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "w的估计误差：tensor([-3.0637e-04, -2.7895e-05])\n",
      "b的估计误差：tensor([-0.0005])\n"
     ]
    }
   ],
   "source": [
    "w = net[0].weight.data\n",
    "print(f'w的估计误差：{true_w - w.reshape(true_w.shape)}')\n",
    "b = net[0].bias.data\n",
    "print(f'b的估计误差：{true_b - b}')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}